package org.zjx.util;


import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.platform.win32.WinDef.RECT;
import org.zjx.entity.Coordinate;

import java.awt.*;
import java.util.ArrayList;
import java.util.List;

public class HwndUtil {
    public static List<HWND> getHwndS(String className, String titleName) {
        List<HWND> hs = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            HWND before = null;
            if (!hs.isEmpty()) before = hs.get(hs.size() - 1);
            HWND hwnd1 = User32.INSTANCE.FindWindowEx(null, before, className, titleName);
            if (hwnd1 != null) {
                hs.add(hwnd1);
            }
        }
        return hs;
    }

    public static boolean haveHwnd(HWND hwnd) {
        return User32.INSTANCE.IsWindowVisible(hwnd);
    }

    public static HWND getHwnd(String className, String titleName) {
        List<HWND> hs = getHwndS(className, titleName);
        if (!hs.isEmpty()) return hs.get(0);
        return null;
    }

    public static RECT getWindowRect(HWND hwnd) {
        RECT rect = new RECT();
        User32.INSTANCE.GetWindowRect(hwnd, rect);
        return rect;
    }

    public static void preposition(HWND hwnd) {
        User32.INSTANCE.SetForegroundWindow(hwnd);
    }

    public static void moveWindow(HWND hwnd, int x, int y) {
        User32.INSTANCE.ShowWindow(hwnd, 9); // Restore the window (SW_RESTORE)
        preposition(hwnd);
        RECT rect = getWindowRect(hwnd);
        int width = rect.right - rect.left;
        int height = rect.bottom - rect.top;
        User32.INSTANCE.MoveWindow(hwnd, x, y, width, height, true);
    }

    public static RECT conversion(int left, int top, int right, int bottom) {
        RECT rect = new RECT();
        rect.left = left;
        rect.top = top;
        rect.right = right;
        rect.bottom = bottom;
        return rect;
    }

    public static Coordinate center(RECT rect) {
        return new Coordinate((rect.right - rect.left + 1)/2, (rect.bottom - rect.top + 1)/2);
    }

    public static Rectangle toRectangle(RECT rect) {
        return new Rectangle(rect.left, rect.top, rect.right-rect.left+1, rect.bottom-rect.top+1);
    }

}
